<template>
  <van-form ref="from_list" @submit="from.onSubmit" validate-first>
    <van-cell-group inset>
      <van-field v-model="from.phone" type="tel" name="手机号码" label="手机号码" placeholder="手机号码"
        :rules="[{ validator: from.isPhone }]" style="height: 55px;" />
      <van-field v-model="from.DynamicVerificationCode" center clearable placeholder="请输入动态验证码"
        :rules="[{ required: true, message: '请输入验证码' }]" label-width="100px">
        <template #label>
          <div style="width: 100%;" @click="getCode">
            <img style="width:100%" :src="`data:image/png;base64,${baEmployee}`" />
          </div>
        </template>
      </van-field>
      <van-field v-model="from.sms" center clearable label="短信验证码" placeholder="请输入短信验证码"
        :rules="[{ required: true, message: '请输入验证码' }]" style="height: 50px;">
        <template #button>
          <van-button size="small" v-if="statusSecond.sendAuthCode" type="primary" @click="statusSecond.send">发送验证码
          </van-button>
          <div v-else>{{ statusSecond.second + '秒' }}</div>
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
  </van-form>
  <van-notify v-model:show="show" type="success" background="#ff976a">
    <span>{{ message }}</span>
  </van-notify>
  <van-action-sheet v-model:show="isActionSheet" :actions="actions" @select="onSelect" />
</template>
<script setup>
import { isPhone } from '@/utils/validate.js'
import { employee, login, isCode, sendMsg } from '@/api/user.js'
import { Dialog, Toast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { useCounterStore } from '@/pinia/user.js'
import { nextTick } from 'vue'

const CounterStor = useCounterStore()
let send = false
const router = useRouter()
const route = useRoute()
const query = route.query
const isShow = ref(false)
const isActionSheet = ref(false)
const actions = reactive([
  { name: '正式工', key: 'regular' },
  { name: '小时工', key: 'Hours' },
  { name: '派遣工', key: 'dispatched' },
  { name: '应届生', key: 'trainee' },
])


function onSelect(value) {
  CounterStor.setHireType(value.key)
  router.push('/home')
}
// 验证是否通过二维码扫描进入的
function modeEntry() {
  let a = false
  if (query?.key) {
    //  正式工    小时工    派遣工    实习生
    const arr = ['regular', 'Hours', 'dispatched', 'trainee']
    // 防止用户手动输入的内容
    a = arr.includes(query.key)
  }
  if(query.isAttribution) CounterStor.setIsAttribution(query.isAttribution)
  // // 通过接口直接进入   提示
  // if (!a) Toast('请通过扫码方式进入！！！！')
  // 通过扫码进来的确认填写内容
  if (a) { CounterStor.setHireType(query.key) }
  isShow.value = a
  return a
}
// 界面渲染结束后调用  判断是否通过扫描二维码进入
nextTick(() => {
  modeEntry()
})

const from = reactive({
  phone: '',
  sms: '',
  DynamicVerificationCode: '',
  onSubmit: async function () {
    // 验证是否通过二维码扫描进入的

    const res = await CounterStor.login(from)
    if (!res.success) return Dialog.alert({ message: res.message })
    CounterStor.getMobulde(from.phone)
    if (!modeEntry()) { isActionSheet.value = true } else { router.push('/home') }
  },
  isPhone: function (value) {
    if (value) {
      if (isPhone(value)) {
        send = true
        return true
      } else {
        return '请输入正确的手机号码'
      }
    } else {
      return '手机号码不允许为空'
    }

  }
})



const plusOne = computed(() => {
  return Store.getters['num']
})
const Store = useStore()

onMounted(() => {
  getEmployee()
  // console.log(import.meta.env.VITE_APP_URL)
})

// 切换验证码
const getCode = function () {
  getEmployee()
}



// bs64 动态验证码
const baEmployee = ref('')

// 获取动态验证码截图
const getEmployee = async function () {
  // const a = await Store.dispatch('getType1', '1')
  const res = await employee()
  if (res.success) {
    baEmployee.value = res.message
  } else {
    showNotify(res)
  }
}

//
const show = ref(false);
const message = ref('')

const showNotify = (res) => {
  show.value = true;
  message.value = res.message
  setTimeout(() => {
    show.value = false;
  }, 2000);
};


const statusSecond = reactive({
  second: 60,     /* 一分钟 倒计时*/
  sendAuthCode: true,       /* 布尔值，通过v-show控制显示‘获取按钮’还是‘倒计时’ */
  timer: null,      /* 倒计时 计数器,防止点击的时候触发多个setInterval*/
  /**
    * 发送验证码 === `点击按钮操作,点击按钮操作,点击按钮操作`
  * */
  send: async function () {
    if (!send) return Dialog.alert({ message: '请确认手机号码' })
    const res = await isCode(from.DynamicVerificationCode)
    if (!res.success) return Dialog.alert({ message: '请确认动态验证码' })
    const sms = await sendMsg({ mobile: from.phone })
    if (!sms.success) return Dialog.alert({ message: sms.message })
    if (statusSecond.sendAuthCode) {
      statusSecond.sendAuthCode = false;
      let interval = window.setInterval(function () {
        setStorage(statusSecond.second);
        if (statusSecond.second-- <= 0) {
          /* 如果 倒计时完毕 重新赋值*/
          statusSecond.second = 60;
          statusSecond.sendAuthCode = true;
          window.clearInterval(interval);
        }
      }, 1000);
    }
  }
})
/**
 * 存储 验证码 防止刷新
 * `用处`: 防止页面刷新 发送验证码状态改变
 * */
const setStorage = (parm) => {
  localStorage.setItem("dalay", parm);
  localStorage.setItem("_time", new Date().getTime());
};
/**
 * 获取 缓存 数据
 * `用处`: 防止页面刷新 发送验证码状态改变
 * */
const getStorage = () => {
  let localDelay = {};
  localDelay.delay = localStorage.getItem("dalay");
  localDelay.sec = localStorage.getItem("_time");
  return localDelay;
}
/**
 *  判断
 *  */
const judgeCode = () => {
  // 获取缓存中的数据
  let localDelay = getStorage();
  let secTime = parseInt(
    (new Date().getTime() - localDelay.sec) / 1000
  );
  if (secTime > localDelay.delay) {
    statusSecond.sendAuthCode = true;
  } else {
    statusSecond.sendAuthCode = false;
    let _delay = localDelay.delay - secTime;
    statusSecond.second = _delay;
    statusSecond.timer = setInterval(() => {
      if (_delay > 1) {
        _delay--;
        setStorage(_delay);
        statusSecond.second = _delay;
        statusSecond.sendAuthCode = false;
      } else {
        // 让浏览器打开的时候,显示剩余的时间
        statusSecond.sendAuthCode = true;
        window.clearInterval(statusSecond.timer);
      }
    }, 1000);
  }
}

/**
 * 页面执行
 */
judgeCode()
</script>
